using Senparc.Weixin.Exceptions;
using Senparc.Weixin.HttpUtility;
using Senparc.Weixin.MP.AppStore.Api;
using System;
using System.Collections.Generic;
namespace Senparc.Weixin.MP.AppStore
{
	public class AppStoreManager
	{
		public const string DEFAULT_URL = "http://api.weiweihi.com:8080";
		public const string BasicApiPath = "/App/Api/";
		private static PassportCollection _passportCollection;
		public static PassportCollection PassportCollection
		{
			get
			{
				if (AppStoreManager._passportCollection == null)
				{
					AppStoreManager._passportCollection = new PassportCollection();
				}
				return AppStoreManager._passportCollection;
			}
			set
			{
				AppStoreManager._passportCollection = value;
			}
		}
		public static PassportBag GetPassportBag(string appKey)
		{
			PassportBag result;
			if (AppStoreManager.PassportCollection.ContainsKey(appKey))
			{
				result = AppStoreManager.PassportCollection[appKey];
			}
			else
			{
				result = null;
			}
			return result;
		}
		private static void Register(string appKey, string secret, string url = "http://api.weiweihi.com:8080", bool getPassportImmediately = false)
		{
			AppStoreManager.PassportCollection.BasicUrl = url + "/App/Api/";
			AppStoreManager.PassportCollection[appKey] = new PassportBag(appKey, secret, url + "/App/Api/");
			if (getPassportImmediately)
			{
				AppStoreManager.ApplyPassport(appKey, secret, url);
			}
		}
		public static void ApplyPassport(string appKey, string appSecret, string url = "http://api.weiweihi.com:8080")
		{
			if (!AppStoreManager.PassportCollection.ContainsKey(appKey))
			{
				AppStoreManager.Register(appKey, appSecret, url, true);
			}
			PassportBag passportBag = AppStoreManager.PassportCollection[appKey];
			string url2 = AppStoreManager.PassportCollection.BasicUrl + "GetPassport";
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			dictionary["appKey"] = passportBag.AppKey;
			dictionary["secret"] = passportBag.AppSecret;
			PassportResult passportResult = Post.PostGetJson<PassportResult>(url2, null, dictionary, null, 10000);
			if (passportResult.Result != AppResultKind.成功)
			{
				throw new WeixinException("获取Passort失败！错误信息：" + passportResult.Result, null);
			}
			passportBag.Passport = passportResult.Data;
			passportBag.Passport.ApiUrl = AppStoreManager.PassportCollection.BasicUrl;
		}
		public static void RemovePassport(string appKey)
		{
			try
			{
				AppStoreManager.PassportCollection.Remove(appKey);
			}
			catch
			{
			}
		}
		public static ApiContainer GetApiContainer(string appKey, string appSecret, string url = "http://api.weiweihi.com:8080")
		{
			return new ApiContainer(appKey, appSecret, url);
		}
	}
}
